package cn.edu.scnu.rabbitmq.test;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import org.junit.Before;
import org.junit.Test;

public class DirectMode {
    private Channel channel;

    @Before
    public void initChannel() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.126.129");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
    }

    @Test
    public void send() throws Exception {
        channel.exchangeDeclare("direct01", "direct");
        channel.exchangeDeclare("direct02", "direct");
        channel.exchangeDeclare("direct03", "direct");

        channel.queueDeclare("Test1", false, false, false, null);
        channel.queueDeclare("Test2", false, false, false, null);
        channel.queueDeclare("Test3", false, false, false, null);

        channel.queueBind("Test1", "direct01", "1");
        channel.queueBind("Test2", "direct02", "2");
        channel.queueBind("Test3", "direct03", "3");

        channel.basicPublish("direct01", "1", null, "1Test".getBytes());
        channel.basicPublish("direct02", "2", null, "2Test".getBytes());
        channel.basicPublish("direct03", "3", null, "3Test".getBytes());
    }

    @Test
    public void consumer01() throws Exception {
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("Test1", false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println("Consumer1: " + new String(delivery.getBody()));
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }

    @Test
    public void consumer02() throws Exception {
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("Test2", false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println("Consumer2: " + new String(delivery.getBody()));
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

    }
}
